package uk.co.richardwkirk.parkrun.android;

import java.util.Collection;

import uk.co.richardwkirk.parkrun.geo.Region;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class CountrySelectionDisplay extends ListActivity {

	ArrayAdapter<String> adapter = null;

	public static final int RESULT_NO_COUNTRIES_FOUND = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Get a list adapter to add the array values into the list
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
		setListAdapter(adapter);
		
		// Add the countries into the list
		displayCountries();
	}

	public void displayCountries() {
		if (ParkrunEventData.getSingleton().isLoaded()) {
			Collection<Region> countries = ParkrunEventData.getSingleton().getWorld().getSubRegions();
			for (Region country : countries) {
				adapter.add(country.getName());
			}
		}
		else {
			Intent intent = this.getIntent();
			this.setResult(RESULT_NO_COUNTRIES_FOUND, intent);
			finish();	
		}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// Get the selected country
		String selectedCountry = adapter.getItem(position);
		Log.d("PARKRUN", "Country selected [" + selectedCountry + "]");

		// Return it!
		Intent data = new Intent();
		data.putExtra(IntentExtras.EXTRA_SELECTED_COUNTRY, selectedCountry);
		setResult(RESULT_OK, data);
		finish();
	}
	
}

